import React, { useState, useEffect, useMemo } from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import s from './style.module.css';
import Table from '@knownsec/react-component/dist/Table';
import KSelect from '@knownsec/react-component/dist/Select';
import KDialog from '@knownsec/react-component/dist/Dialog';
import Form from '@knownsec/react-component/dist/Form';
import KInput from '@knownsec/react-component/dist/Input';
import Textarea from '@knownsec/react-component/dist/Textarea';
import Tooltip from '@knownsec/react-component/dist/Tooltip';
import w from '../../Jobs/style.module.css';
import Message from '@knownsec/react-component/dist/Message';
import moment from 'moment';

import {
	httpCol,
	httpMap,
	jobCol,
} from '../../../JobManage/WebTask/TaskDetail/columns';
import EmptyData from '../../../../components/empty/EmptyData';
import Button from '@knownsec/react-component/dist/Button';
import fetchFer from 'API/fetch';
import { turnToUrlparam } from '../../../../helpers/getUrlParams';
import Icon from '@knownsec/react-component/dist/Icon';
import CopyBoard from '../../../../components/CopyBoard';

function Info({ row }) {
	const [webForm] = Form.useForm();
	const [creatWebVisible, setCreatWebVisible] = useState(false);
	const [isCreate, setIsCreate] = useState(true);
	const [webRecord, setWebRecord] = useState(null);
	const [hostInfo, setHostInfo] = React.useState({});
	const [resultWeb, setResultWeb] = useState(null);
	const [resultWebVisible, setResultWebVisible] = useState(false);
	const validatormap = (rule, value) => {
		if (rule.field === 'note') {
			if (!value || !value.trim()) {
				return Promise.reject('请输入资产名称');
			} else if (!(value.trim().replace(/[a-zA-Z0-9_\u4E00-\u9FA5]{1,50}/g, '').length === 0)) {
				return Promise.reject('名称格式错误，只能输入1～50个中文、英文字母、数字、下划线');
			} else {
				return Promise.resolve();
			}
			// eslint-disable-next-line prefer-promise-reject-errors
		} else {
			return Promise.resolve();
		}
	}
	const handleCreateJob = async record => {
		if (!isCreate) return false;
		webForm.current.validateFields().then(async res => {
			if (res) {
				setIsCreate(false);
				const url = '/api/v2/asset/asset_add';
				const addData = {
					note: res.note,
					target_url: res.protocol[0] + res.url,
					asset_type: 'web',
					source_ips: res.source_ip.split('\n'),
				};
				const resp = await fetchFer(url, {
					method: 'POST',
					body: JSON.stringify(addData),
					checkStatus: 501,
				});
				setIsCreate(true);
				if (resp?.message?.indexOf('失败') > -1) {
					setResultWeb(resp.data);
					setCreatWebVisible(false);
					setResultWebVisible(true);
				} else {
					if (resp.code === 0) setCreatWebVisible(false);
					Message.show({
						type: resp.code === 0 ? 'success' : 'error',
						message: resp.message || resp.msg,
						onclose() {
							if (resp.code === 0) {
								window.location.href = `/#/asset-manage/manage/web?filter=${encodeURI(
									JSON.stringify({ target_url: webRecord.target_url })
								)}`;
							}
						},
					});
				}
				return resp;
			}
		});
	};
	const getData = async (num, size) => {
		const sendData = {
			job_id: row.job_id,
		};
		const params = turnToUrlparam(sendData);
		const host = await fetchFer(
			`/api/v2/tasks/asset/detail/overview?${params}`,
			{
				method: 'GET',
			}
		).catch(error => {
			return null;
		});
		const subdomain = host.results?.subdomain?.map(item => {
			if (!item.accessed) {
				const protocol = [item.url.split('//')[0] + '//'];
				const url = item.url.split('//')[1];
				item.method = (
					<Button
						pro
						type="text"
						className={cn(s.p0, s.hAuto)}
						onClick={() => {
							setWebRecord({
								note: '',
								target_url: item.url,
								source_ip: item.ip,
							});
							webForm.current.setFieldsValue({
								note: '',
								target_url: item.url,
								source_ip: item.ip,
								protocol,
								url,
							});
							setCreatWebVisible(true);
						}}
					>
						接入资产
					</Button>
				);
			} else {
				item.method = (
					<Button
						pro
						type="text"
						className={cn(s.p0, s.hAuto)}
						onClick={() => {
							window.location.href = `/#/asset-manage/manage/web?filter=${encodeURI(
								JSON.stringify({ target_url: item.url })
							)}`;
						}}
					>
						查看资产
					</Button>
				);
			}
			return item;
		});
		setHostInfo(host.results ? { ...host.results, subdomain } : {});
	};
	const httpMe = (http_method = '') => {
		const resHttp =
			http_method.length > 0
				? http_method.split(',').map(item => {
						return item.toUpperCase();
				  })
				: [];
		return Object.keys(httpMap).map(i => {
			return {
				type: i,
				isSafe:
					resHttp.length === 0 ||
					resHttp.indexOf(i) === -1 ||
					(resHttp.indexOf(i) > -1 &&
						['HEAD', 'GET', 'OPTIONS'].indexOf(i) > -1),
				isClose: resHttp.length === 0 || resHttp.indexOf(i) === -1,
			};
		});
	};
	useEffect(() => {
		getData();
	}, [row]);
	return (
		<div>
			<div className={cn(s.item)}>
				<div className={cn(s.flex, s.aic)}>
					最近更新时间：
					<span className={cn(s.pl10, s.pr20)}>
						{row.update_time
							? moment(row.update_time).format('YYYY-MM-DD HH:mm:ss')
							: '- -'}
					</span>
				</div>
				<p className={s.itemTitle}>基本信息</p>
				<div className={s.textBox}>
					<div className={cn(s.df, s.aic, s.mb16)}>
						<div className={cn(s.flex1)}>
							网站标题：
							{hostInfo.basic_info?.title ? (
								<CopyBoard
									text={hostInfo.basic_info?.title}
									maxWidth="16rem"
								></CopyBoard>
							) : (
								'- -'
							)}
						</div>
						<div
							className={cn(s.flex1, s.ell)}
							title={
								`${hostInfo.ipdb?.country_name || ''}${
									hostInfo.ipdb?.region_name
										? ' - ' + hostInfo.ipdb?.region_name
										: ''
								}${
									hostInfo.ipdb?.city_name
										? ' - ' + hostInfo.ipdb?.city_name
										: ''
								}` || '- -'
							}
						>
							地理位置：
							{`${hostInfo.ipdb?.country_name || ''}${
								hostInfo.ipdb?.region_name
									? ' - ' + hostInfo.ipdb?.region_name
									: ''
							}${
								hostInfo.ipdb?.city_name ? ' - ' + hostInfo.ipdb?.city_name : ''
							}` || '- -'}
						</div>
						<div className={cn(s.flex1)}>
							IP地址：{hostInfo.port?.ip || '- -'}
						</div>
					</div>
					<div className={cn(s.df, s.aic)}>
						<div className={cn(s.flex1)}>
							ICP备案：
							{hostInfo.icp?.desc === '已备案'
								? `${hostInfo.icp?.desc}${
										hostInfo.icp?.icp ? `（${hostInfo.icp?.icp}）` : ''
								  }`
								: hostInfo.icp?.desc || '- -'}
						</div>
						<div className={cn(s.flex1)}>
							可用性：
							{hostInfo?.http_get ? +hostInfo?.http_get?.status >= 200 &&
								+hostInfo?.http_get?.status < 300
								? '正常' : '异常' : '- -'}
						</div>
						<div
							className={cn(s.flex1, s.ell)}
							title={hostInfo.waf_list?.join('，') || '- -'}
						>
							防御信息：{hostInfo.waf_list?.join('，') || '- -'}
						</div>
					</div>
				</div>
			</div>
			<div className={s.item}>
				<p className={s.itemTitle}>HTTP方法</p>
				<div className={s.tableBox}>
					<Table
						columns={httpCol}
						pro
						data={httpMe(hostInfo?.http_method)}
						className={s.infoTable}
					/>
				</div>
			</div>
			<div className={s.item}>
				<p className={s.itemTitle}>
					开放端口
					{hostInfo?.port?.data.length > 0 &&
						`（${hostInfo?.port?.data.length}）`}
				</p>
				<Table
					columns={[
						{
							title: '端口',
							dataIndex: 'port',
							key: 'port',
						},
						{
							title: '服务名称',
							dataIndex: 'name',
							key: 'name',
						},
					]}
					pro
					empty={<EmptyData className={s.nobor} type="img" />}
					scroll={hostInfo?.port?.data?.length > 10 ? { y: 470 } : false}
					data={hostInfo?.port?.data}
					className={s.infoTable}
				/>
			</div>
			<div className={s.item}>
				<p className={s.itemTitle}>
					关联资产信息
					{hostInfo?.subdomain?.length > 0 &&
						`（${hostInfo?.subdomain?.length}）`}
				</p>
				<Table
					columns={jobCol}
					pro
					empty={<EmptyData className={s.nobor} type="img" />}
					scroll={hostInfo?.subdomain?.length > 10 ? { y: 470 } : false}
					data={hostInfo?.subdomain}
					className={s.infoTable}
				/>
			</div>
			<KDialog
				visible={creatWebVisible}
				className={s.w550}
				title="添加资产"
				onhide={() => {
					setCreatWebVisible(false);
					webForm.current.resetFields();
				}}
				onsubmit={handleCreateJob}
			>
				<div className={cn(w.p20_0, w.createForm)}>
					<Form
						ref={webForm}
						labelCol={{ span: 5 }}
						onValuesChange={(newItem, allValues) => {
							const val = recursion(newItem);
							function recursion(obj) {
								const obj_ = obj;
								const key = Object.keys(obj_);
								if (obj_[key] && typeof obj_[key] === 'object') {
									if ({}.propertyIsEnumerable.call(obj_[key], 'value')) {
										obj_[key] = obj_[key].value;
									} else if (
										{}.propertyIsEnumerable.call(obj_[key], 'selectedItem')
									) {
										if (obj_[key].selectedItem.length > 0) {
											if (obj_[key].selectedItem.length > 1) {
												obj_[key] = obj_[key].selectedItem.map(
													item => item.value
												);
											} else {
												obj_[key] = [obj_[key].selectedItem[0].value];
											}
										} else if (obj_[key].selectedItem.length === 0) {
											obj_[key] = [];
										}
									} else {
										obj_[key] = recursion(obj_[key]);
									}
								}
								return obj_;
							}
							webForm.current.setFieldsValue(val);
						}}
						wrapperCol={{ span: 18 }}
						initialValues={{ remember: true }}
					>
						<Form.Item
							label="资产名称"
							name="note"
							rules={[{ required: true, validator: validatormap }]}
						>
							<KInput placeholder="请输入资产名称" />
						</Form.Item>
						<Form.Item
							label="资产地址"
							name="url"
							rules={[{ required: true, message: '请输入资产地址' }]}
						>
							<div className={cn(w.df, w.aic, w.bdt, 'error-box')}>
								<Form.Item noStyle name="protocol">
									<KSelect
										className={cn(w.w80, w.appendSelect)}
										option={[
											{ label: 'http://', value: 'http://' },
											{ label: 'https://', value: 'https://' },
										]}
									/>
								</Form.Item>
								<Form.Item noStyle name="url">
									<KInput className={w.flex1} placeholder="请输入资产地址" />
								</Form.Item>
								<Tooltip
									overlay={
										<div>
											协议+子域名/IPv4/IPv6+端口
											<br />
											示例：http://www.example.com:80
											<br />
											<span className="_tipSpan_7z5aq_29">
												http://[AD80:0000:0000:0000:ABAA:0000:00C2:0002]
											</span>
											<br />
											<span className="_tipSpan_7z5aq_29">https://1.1.1.1</span>
											<br />
										</div>
									}
									placement="top"
									children={
										<Icon
											type="question"
											className={cn(w.cp, w.pa, w.r_20, w.fs20)}
										/>
									}
								></Tooltip>
							</div>
						</Form.Item>
						<Form.Item
							label="源站IP"
							name="source_ip"
							validateStatus="warning"
							help="注：资产认证后，系统默认一周一次监测频率探测资产信息。"
						>
							<Textarea
								rows={4}
								placeholder="请输入源站 IP 地址，若有多个 IP 地址可换行添加，多个源站 IP 算多个资产数量。"
							/>
						</Form.Item>
					</Form>
				</div>
			</KDialog>
			<KDialog
				visible={resultWebVisible}
				className={s.w700}
				title="提示"
				cancelText={
					resultWeb?.summary?.success ? (
						<span
							onClick={() => {
								window.location.href = `/#/asset-manage/manage/web?filter=${encodeURI(
									JSON.stringify({ target_url: webRecord.target_url })
								)}`;
							}}
						>
							前往Web资产列表
						</span>
					) : (
						'取消'
					)
				}
				onhide={e => {
					setResultWeb(null);
					setResultWebVisible(false);
				}}
				onsubmit={() => setResultWebVisible(false)}
			>
				{resultWeb && (
					<div className={s.p20_0}>
						<div className={s.mb20}>
							共计：{resultWeb?.summary?.total}
							<span className={s.m0_20}>
								成功：{resultWeb?.summary?.success}
							</span>
							失败：{resultWeb?.summary?.fail}
						</div>
						<div className={s.mb10}>添加失败的资产如下：</div>
						<Table
							columns={[
								{
									title: '资产名称',
									key: 'note',
									dataIndex: 'note',
									render(e) {
										return (
											<Tooltip overlay={e} placement="top">
												<span>{e}</span>
											</Tooltip>
										);
									},
								},
								{
									title: '资产地址',
									key: 'target_url',
									dataIndex: 'target_url',
									render(e) {
										return (
											<Tooltip overlay={e} placement="top">
												<span>{e}</span>
											</Tooltip>
										);
									},
								},
								{ title: '源站IP', key: 'source_ip', dataIndex: 'source_ip' },
								{
									title: '失败原因',
									key: 'reason',
									dataIndex: 'reason',
									render(e) {
										return (
											<Tooltip overlay={e} placement="top">
												<span>{e}</span>
											</Tooltip>
										);
									},
								},
							]}
							data={resultWeb?.detail}
						/>
					</div>
				)}
			</KDialog>
		</div>
	);
}
Info.propTypes = {
	row: PropTypes.any,
};
export default Info;
